<?php

use Mapper\OrderModel as OrderMapper;
use Mapper\OrderRefundModel as RefundMapper;
use Mapper\MemberModel as MemberMapper;
use Mapper\SparringbuysModel as BuyMapper;
use Mapper\SparringbuydetailModel as BuyDetailMapper;
use Mapper\SparringsellModel as SellMapper;
use Mapper\ComplaintModel as ComplaintMapper;
use Mapper\SparringgameModel as GameMapper;
use Mapper\EvaluateModel as EvaluateMapper;

class OrderController extends \Base\ApiController {

    public $statusToWord = [
        1 => '待支付',
        2 => '已支付',
        3 => '退款中',
        4 => '拒绝退款',
        5 => '已退款',
        6 => '已完成',
        7 => '已评价',
        8 => '已关闭',
    ];

    /**
     * @desc 添加订单信息
     *
     * @return false
     */
    public function addAction() {
        $request    = $this->getRequest();
        $fromUid    = (int)$request->get('from_uid');
        $toUid      = \Lib\User::getInstance()->id();
        $price      = (float)$request->get('price', 0.00);
        $payPrice   = (float)$request->get('pay_price', 0.00);
        $type       = (int)$request->get('type', 1);
        $sparringNo = (string)$request->get('sparring_no');
        $envelopeId = (int)$request->get('envelope_id'); //暂时不使用
        $duration   = (int)$request->get('duration');
        $remark     = (string)trim($request->get('remark'));

        if($fromUid < 65535 || $fromUid === $toUid) {
            return \Response::error('无效的uid', 10601);
        }

        if($price <= 0) {
            return \Response::error('原价价格有误', 10602);
        }

        if($payPrice <= 0) {
            return \Response::error('支付价格有误', 10603);
        }

        $memberMapper = MemberMapper::getInstance();
        $fromUidModel = $memberMapper->findById($fromUid);
        $toUidModel   = $memberMapper->findById($toUid);

        if(!$fromUidModel instanceof \MemberModel || !$toUidModel instanceof \MemberModel) {
            return \Response::error('无效的uid', 10601);
        }

        if($type === \Lib\Consts::ORDER_TYPE_SPARRING_BUY) {
            $buyDetailMapper = BuyDetailMapper::getInstance();
            $sparringNoArr   = $sparringNo;

            if(strpos($sparringNo, ',') !== false) {
                $sparringNoArr = explode(',', $sparringNo);
            }

            $buyDetailModels = $buyDetailMapper->fetchAll(['id' => $sparringNoArr]);

            if(empty($buyDetailModels)) {
                return \Response::error('看大腿id信息有误', 10604);
            }

            foreach($buyDetailModels as $buyDetailModel) {
                if($buyDetailModel->getBegin_time() < time()) {
                    return \Response::error('包含过期陪练时段, 请重新下单', 10621);
                }

                if($buyDetailModel->getStatus() !== \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL) {
                    return \Response::error('陪练已被他人抢购, 请重新下单', 10620);
                }
            }

            $data = [
                'status' => \Lib\Consts::SPARRING_DETAIL_STATUS_PAY,
            ];

            try {
                $rows = $buyDetailMapper->update($data, [
                    'id'             => $sparringNoArr,
                    'status'         => \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL,
                    'begin_time > ?' => time(),
                ]);

                if($rows <= 0) {
                    return \Response::error('看大腿状态更新失败', 10605);
                }
            } catch(\Exception $exc) {
                return \Response::error('异常信息报错', 10100);
            }
        } elseif($type === \Lib\Consts::ORDER_TYPE_SPARRING_SELL) {
            if($duration <= 0) {
                return \Response::error('无效的时长', 10315);
            }

            $sellMapper = SellMapper::getInstance();
            $sellModel  = $sellMapper->findById($sparringNo);

            if(!$sellModel instanceof \SparringSellModel) {
                return \Response::error('无效的求大腿id', 10622);
            }

            $data = [
                'status' => \Lib\Consts::SPARRING_DETAIL_STATUS_PAY,
            ];

            try {
                $rows = $sellMapper->update($data, [
                    'id'     => $sparringNo,
                    'status' => \Lib\Consts::SPARRING_SELL_STATUS_NORMAL,
                ]);

                if($rows <= 0) {
                    return \Response::error('求大腿状态更新失败', 10606);
                }
            } catch(\Exception $exc) {
                return \Response::error('异常信息报错', 10100);
            }
        }

        $orderMapper = OrderMapper::getInstance();

        $model = new \OrderModel();
        $model->setFrom_uid($fromUid);
        $model->setTo_uid($toUid);
        $model->setPrice($price);
        $model->setPay_price($payPrice);
        $model->setType($type);
        $model->setStatus(\Lib\Consts::ORDER_STATUS_NOPAY);
        $orderNo = $this->createOrderNo();
        $model->setOrder_no($orderNo);
        $model->setEnvelope_id($envelopeId);
        $model->setSparring_no($sparringNo);
        $model->setAdd_time(time());
        $model->setDuration($duration);
        $model->setRemark($remark);

        try {
            $id = $orderMapper->insert($model);
            return $id > 0 ? \Response::data(['order_id' => $id, 'order_no' => $orderNo]) : \Response::error('创建订单失败', 10607);
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @desc 订单号生成
     *
     * @return string
     */
    public function createOrderNo() {
        return date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    /**
     * @desc 更改订单状态
     *
     * @param $orderId
     * @param $status
     * @return false
     */
    protected function changestatus($orderId, $oldStatus, $newStatus) {
        if($orderId <= 0) {
            return \Response::error('订单id有误', 10608);
        }

        if($oldStatus <= 0 || $oldStatus >= 10 || $newStatus <= 0 || $newStatus >= 10) {
            return \Response::error('订单状态值有误', 10609);
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return \Response::error('无效的订单id', 10610);
        }

        if($orderModel->getStatus() !== $oldStatus) {
            return \Response::error('订单状态值有误', 10609);
        }

        $data = [
            'status'      => $newStatus,
            'update_time' => time(),
        ];

        try {
            $rows = $orderMapper->update($data, ['id' => $orderId, 'status' => $oldStatus]);
            return $rows > 0 ? true : false;
        } catch(\Exception $e) {
            return false;
        }
    }

    /**
     * @desc 更改订单状态
     * @todo 订单状态判断
     * @return false
     */
    public function chgstatusAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');
        $status  = (int)$request->get('status');

        if($orderId <= 0) {
            return \Response::error('订单id有误', 10608);
        }

        if(!isset($this->statusToWord[$status])) {
            return \Response::error('订单状态值有误', 10609);
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return \Response::error('无效的订单id', 10610);
        }

        $orderModel->setStatus($status);

        try {
            $rows = $orderMapper->update($orderModel, ['id' => $orderId]);
            return $rows > 0 ? \Response::data(null) : \Response::error('订单状态变更失败', 10611);
        } catch(\Exception $e) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @desc 订单列表(支出)
     *
     * @return false
     */
    public function outlistAction() {
        $uid         = \Lib\User::getInstance()->id();
        $return      = [];
        $request     = $this->getRequest();
        $page        = (int)$request->get('page', 1);
        $perPage     = (int)$request->get('per_page', 15);
        $page        = max(1, $page);
        $perPage     = min(30, $perPage);
        $limit       = $perPage;
        $offset      = $limit * ($page - 1);
        $orderMapper = OrderMapper::getInstance();
        $orderModels = $orderMapper->fetchAll([
            'to_uid'     => $uid,
            'status < ?' => 9,
        ], 'add_time DESC', $limit, $offset);

        if(empty($orderModels)) {
            return \Response::data([]);
        }

        $memberMapper = MemberMapper::getInstance();
        $gameMapper   = GameMapper::getInstance();

        foreach($orderModels as $orderModel) {
            $data        = $orderModel->toArray();
            $type        = (int)$orderModel->getType();
            $sparringId  = $orderModel->getSparring_no();
            $fromUid     = $orderModel->getFrom_uid();
            $memberModel = $memberMapper->findById($fromUid);

            if(!$memberModel instanceof \MemberModel) {
                return \Response::error('无效的uid', 10612);
            }

            $data['avatar']      = $memberModel->getAvatar();
            $data['nick_name']   = urldecode($memberModel->getNick_name());
            $status              = $orderModel->getStatus();
            $data['status_word'] = isset($this->statusToWord[$status]) ? $this->statusToWord[$status] : '';

            if($type === 1) { // 看大腿
                if(strpos($sparringId, ',') !== false) {
                    $sparringId = explode(',', $sparringId);
                }

                $buyDetailMapper = BuyDetailMapper::getInstance();
                $detailModel     = $buyDetailMapper->fetch(['id' => $sparringId], 'begin_time');
                $gameModel       = $gameMapper->findById($detailModel->getGame_id());

                if(!$gameModel instanceof \SparringGameModel) {
                    $data['game_name'] = '';
                } else {
                    $data['game_name'] = $gameModel->getGame_name();
                }

                $data['time_interval'] = date('H:i', $detailModel->getBegin_time()) . '-' .
                    date('H:i', $detailModel->getEnd_time());
                $data['count']         = count($sparringId);
            } elseif($type === 2) { // 求大腿
                $sellMapper = SellMapper::getInstance();
                $sellModel  = $sellMapper->findById($sparringId);

                if(!$sellModel instanceof \SparringSellModel) {
                    return \Response::error('无效的求大腿id');
                }

                $gameModel = $gameMapper->findById($sellModel->getGame_id());

                if(!$gameModel instanceof \SparringGameModel) {
                    $data['game_name'] = '';
                } else {
                    $data['game_name'] = $gameModel->getGame_name();
                }

                $data['time_interval'] = date('m月d日 H:i', $sellModel->getBegin_time()) . '-' .
                    date('m月d日 H:i', $sellModel->getEnd_time());
            }

            $date          = date('Y-m-d', $orderModel->getAdd_time());
            $tmp['data'][] = $data;
            $tmp['date']   = $date;

            if(isset($return[$date])) {
                $return[$date]['data'][] = $data;
            } else {
                $return[$date] = $tmp;
            }

            unset($tmp);
            unset($date);
            unset($data);
        }

        if(!empty($return)) {
            $return = array_values($return);
        }

        return \Response::data($return);
    }

    /**
     * @desc 订单收益(收入)
     *
     * @return false
     */
    public function inlistAction() {
//        $uid         = \Lib\User::getInstance()->id();
        $uid         = 65535;
        $return      = [];
        $request     = $this->getRequest();
        $page        = (int)$request->get('page', 1);
        $perPage     = (int)$request->get('per_page', 15);
        $page        = max(1, $page);
        $perPage     = min(30, $perPage);
        $limit       = $perPage;
        $offset      = $limit * ($page - 1);
        $orderMapper = OrderMapper::getInstance();
        $orderModels = $orderMapper->fetchAll([
            'from_uid'   => $uid,
            'status < ?' => 9,
        ], 'add_time DESC', $limit, $offset);

        if(empty($orderModels)) {
            return \Response::data([]);
        }

        $memberMapper = MemberMapper::getInstance();
        $gameMapper   = GameMapper::getInstance();

        foreach($orderModels as $orderModel) {
            $data        = $orderModel->toArray();
            $type        = (int)$orderModel->getType();
            $sparringId  = $orderModel->getSparring_no();
            $toUid       = $orderModel->getTo_uid();
            $memberModel = $memberMapper->findById($toUid);

            if(!$memberModel instanceof \MemberModel) {
                return \Response::error('无效的uid', 10612);
            }

            $sellMapper          = SellMapper::getInstance();
            $buyDetailMapper     = BuyDetailMapper::getInstance();
            $status              = $orderModel->getStatus();
            $data['status_word'] = isset($this->statusToWord[$status]) ? $this->statusToWord[$status] : '';
            $data['avatar']      = $memberModel->getAvatar();
            $data['nick_name']   = urldecode($memberModel->getNick_name());

            if($type === 1) { // 看大腿
                if(strpos($sparringId, ',') !== false) {
                    $sparringId = explode(',', $sparringId);
                }

                $detailModel = $buyDetailMapper->fetch(['id' => $sparringId], 'begin_time');
                $gameModel   = $gameMapper->findById($detailModel->getGame_id());

                if(!$gameModel instanceof \SparringGameModel) {
                    $data['game_name'] = '';
                } else {
                    $data['game_name'] = $gameModel->getGame_name();
                }

                $data['time_interval'] = date('H:i', $detailModel->getBegin_time()) . '-' .
                    date('H:i', $detailModel->getEnd_time());
                $data['count']         = count($sparringId);
            } elseif($type === 2) { // 求大腿
                $sellModel = $sellMapper->findById($sparringId);
                $gameModel = $gameMapper->findById($sellModel->getGame_id());

                if(!$gameModel instanceof \SparringGameModel) {
                    $data['game_name'] = '';
                } else {
                    $data['game_name'] = $gameModel->getGame_name();
                }

                $data['time_interval'] = date('m月d日 H:i', $sellModel->getBegin_time()) . '-' .
                    date('m月d日 H:i', $sellModel->getEnd_time());
            }

            $date          = date('Y-m-d', $orderModel->getAdd_time());
            $tmp['data'][] = $data;
            $tmp['date']   = $date;

            if(isset($return[$date])) {
                $return[$date]['data'][] = $data;
            } else {
                $return[$date] = $tmp;
            }

            unset($tmp);
            unset($date);
            unset($data);
        }

        if(!empty($return)) {
            $return = array_values($return);
        }

        return \Response::data($return);
    }

    /**
     * @desc 订单详情
     *
     * @return false
     */
    public function detailAction() {
        $request  = $this->getRequest();
        $orderId  = (int)$request->get('order_id');
        $fundFlow = (int)$request->get('fund_flow'); // 1支出  2收入
        $uid      = 0;

        if($orderId <= 0) {
            return \Response::error('订单id有误', 10608);
        }

        if($fundFlow !== 1 && $fundFlow !== 2) { //1支出 2收入
            return \Response::error('无效的收支状态');
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return \Response::error('无效的订单ID', 10610);
        }

        $data                = $orderModel->toArray();
        $data['order_time']  = date('Y-m-d H:i:s', $orderModel->getAdd_time());
        $status              = $orderModel->getStatus();
        $data['status_word'] = isset($this->statusToWord[$status]) ? $this->statusToWord[$status] : '';

        $memberMapper = MemberMapper::getInstance();

        // duifang
        if((int)$fundFlow === 1) {
            $uid = $orderModel->getFrom_uid();
        } elseif((int)$fundFlow === 2) {
            $uid = $orderModel->getTo_uid();
        }

        $memberModel = $memberMapper->findById($uid);

        if(!$memberModel instanceof \MemberModel) {
            return \Response::error('无效的uid', 10612);
        }

        $data['avatar']    = $memberModel->getAvatar();
        $data['nick_name'] = urldecode($memberModel->getNick_name());
        $data['uid']       = $memberModel->getId();
        $data['gender']    = $memberModel->getGender();

        $birthday = $memberModel->getBirthday();
        $age      = date('Y') - date('Y', $birthday) - 1;

        if(date('m', time()) == date('m', $birthday)) {
            if(date('d', time()) > date('d', $birthday)) {
                ++$age;
            }
        } elseif(date('m', time()) > date('m', $birthday)) {
            ++$age;
        }

        $data['age'] = $age;

        $sparringId      = $orderModel->getSparring_no();
        $buyDetailMapper = BuyDetailMapper::getInstance();
        $gameMapper      = GameMapper::getInstance();
        $detailModels    = $buyDetailMapper->fetchAll(['id' => $sparringId], 'begin_time');

        foreach($detailModels as $detailModel) {
            $data['time_interval'][] = date('H:i', $detailModel->getBegin_time()) . '-' .
                date('H:i', $detailModel->getEnd_time());
        }

        $gameModel = $gameMapper->findById($detailModels[0]->getGame_id());

        if(!$gameModel instanceof \SparringGameModel) {
            $data['game_name'] = '';
        } else {
            $data['game_name'] = $gameModel->getGame_name();
        }

        $data['count'] = count($sparringId);

        $refundMapper          = RefundMapper::getInstance();
        $data['sum']           = '';
        $data['reason']        = '';
        $data['finish_time']   = '';
        $data['evl_content']   = '';
        $data['refuse_reason'] = '';

        if($status === 3) {
            $refundOrder    = $refundMapper->findByOrder_id($orderId);
            $data['reason'] = $refundOrder->getReason();
        } elseif($status === 4) {
            $refundOrder           = $refundMapper->findByOrder_id($orderId);
            $data['refuse_reason'] = $refundOrder->getRefuse_reason();
        } elseif($status === 5) {
            $refundOrder = $refundMapper->findByOrder_id($orderId);
            $data['sum'] = $refundOrder->getSum();
        } elseif($status === 6) {
            $data['finish_time'] = $orderModel->getUpdate_time();
        } elseif($status === 7) {
            $data['finish_time'] = $orderModel->getUpdate_time();
            $evaluateMapper      = EvaluateMapper::getInstance();
            $evaluateModel       = $evaluateMapper->findByOrder_id($orderId);
            $data['evl_content'] = '';

            if($evaluateModel instanceof \EvaluateModel) {
                $data['evl_content'] = $evaluateModel->getContent();
            }
        }

        return \Response::data($data);
    }

    /**
     * @desc 退款申请
     *
     * @return false
     */
    public function refundapplyAction() {
        $request = $this->getRequest();
        $sum     = (float)$request->get('sum');
        $reason  = (string)$request->get('reason');
        $orderId = (int)$request->get('order_id');

        if($sum <= 0) {
            return \Response::error('无效的金额', 10615);
        }

        if(empty($reason)) {
            return \Response::error('退款理由不能为空', 10616);
        }

        if($orderId <= 0) {
            return \Response::error('无效的订单id', 10617);
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return \Response::error('无效的订单id', 10617);
        }

        //哪种情况不能退款1-3-5-8
        if(!in_array($orderModel->getStatus(), [2, 4, 6, 7])) {
            return \Response::error('此订单状态不能退款', 10618);
        }

        $refundMapper = RefundMapper::getInstance();
        $model        = new \OrderRefundModel();
        $model->setOrder_id($orderId);
        $model->setSum($sum);
        $model->setReason($reason);
        $model->setStatus(\Lib\Consts::ORDER_REFUND_STATUS_REPLY);
        $model->setAdd_time(time());

        $refundMapper->begin();
        $id = $refundMapper->insert($model);

        if($id <= 0) {
            $refundMapper->rollback();
            return \Response::error('申请退款失败', 10614);
        }

        if(!$this->changestatus($orderId, $orderModel->getStatus(), \Lib\Consts::ORDER_STATUS_REFUNDING)) {
            $refundMapper->rollback();
            return \Response::error('申请退款失败', 10614);
        }

        $refundMapper->commit();
        return \Response::data(null);
    }

    /**
     * @desc 提交申诉
     *
     * @todo 判断何种状态不能进行申诉
     * @return false
     */
    public function addcomplaintAction() {
        $request = $this->getRequest();
        $content = (string)trim($request->get('content', 123));
        $imgUrl  = (string)$request->get('img_url', 123);
        $orderId = (int)$request->get('order_id', 1);

        if($orderId <= 0) {
            return \Response::error('订单id有误', 10608);
        }

        if(empty($content)) {
            return \Response::error('内容不能为空', 10630);
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return \Response::error('无效的订单id', 10610);
        }

        $mapper = ComplaintMapper::getInstance();

        $model = new \ComplaintModel();
        $model->setContent($content);
        $model->setOrder_id($orderId);
        $model->setAdd_time(time());
        $model->setImg_url($imgUrl);
        $model->setStatus(1);

        try {
            $id = $mapper->insert($model);
            return $id > 0 ? \Response::data(null) : \Response::error('申诉提交失败', 10619);
        } catch(\Exception $exc) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    /**
     * @desc 下单前
     *
     * @return false
     */
    public function orderinfoAction() {
        $request    = $this->getRequest();
        $sparringId = (int)$request->get('sparring_id');
        $uid        = \Lib\User::getInstance()->id();
        $type       = (int)$request->get('type', 0);

        if(!in_array($type, [1, 2])) {
            return \Response::error('无效的类型', 10631);
        }

        if($sparringId <= 0) {
            return \Response::error('无效的陪练信息id', 10636);
        }

        $memberMapper = MemberMapper::getInstance();

        if($type === 1) {
            $buyMapper = BuyMapper::getInstance();
            $buyModel  = $buyMapper->findById($sparringId);

            if(!$buyModel instanceof \SparringBuysModel) {
                return \Response::error('无效的看大腿id', 10637);
            }

            $buyDetailMapper = BuyDetailMapper::getInstance();
            $detailModel     = $buyDetailMapper->fetch([
                'sparring_buy_id' => $sparringId,
                'status'          => \Lib\Consts::SPARRING_DETAIL_STATUS_NORMAL,
            ]);

            if(!$detailModel instanceof \SparringBuyDetailModel) {
                return \Response::error('无效的看大腿id', 10638);
            }

            $publisherUid = $buyModel->getUid();

            $return                  = $detailModel->toArray();
            $return['time_interval'] = date('H:i', $detailModel->getBegin_time()) . '-' . date('H:i', $detailModel->getEnd_time());
            $return['can_order']     = ($publisherUid !== $uid ? '1' : '0');
        } elseif($type === 2) {
            $sellMapper = SellMapper::getInstance();
            $sellModel  = $sellMapper->findById($sparringId);

            if(!$sellModel instanceof \SparringSellModel) {
                return \Response::error('无效的求大腿id', 10638);
            }

            $publisherUid = $sellModel->getUid();

            $return                  = $sellModel->toArray();
            $return['time_interval'] = date('H:i', $sellModel->getBegin_time()) . '-' . date('H:i', $sellModel->getEnd_time());
            $return['can_order']     = ($publisherUid === $uid ? '1' : '0');
        } else {
            return \Response::error('无效的类型', 10631);
        }

        $publisherMemberModel = $memberMapper->findById($publisherUid);

        if(!$publisherMemberModel instanceof \MemberModel) {
            return \Response::error('无效的uid', 10601);
        }

        $return['publisher_nickname'] = urldecode($publisherMemberModel->getNick_name());
        $return['publisher_openid']   = $publisherMemberModel->getOpen_id();
        $return['publisher_gender']   = $publisherMemberModel->getGender();
        $return['publisher_avatar']   = $publisherMemberModel->getAvatar();
        $return['publisher_age']      = \Lib\Tool::age($publisherMemberModel->getBirthday());
        $memberModel                  = $memberMapper->findById($uid);
        $return['own_avatar']         = $memberModel->getAvatar();

        return \Response::data($return);
    }

    /**
     * @desc 关闭订单
     *
     * @return false
     */
    public function closeAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');
        $status  = (int)$request->get('status');

        if($orderId <= 0) {
            return \Response::error('订单id有误', 10608);
        }

        if($status !== \Lib\Consts::ORDER_STATUS_NOPAY) {
            return \Response::error('订单不能关闭', 10632);
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return \Response::error('无效的订单id', 10610);
        }

        if($orderModel->getStatus() !== \Lib\Consts::ORDER_STATUS_NOPAY) {
            return \Response::error('订单不能关闭', 10632);
        }

        $data = [
            'status' => \Lib\Consts::ORDER_STATUS_CLOSE,
        ];

        try {
            $rows = $orderMapper->update($data, ['id' => $orderId]);
            return $rows > 0 ? \Response::data(null) : \Response::error('关闭订单失败', 10611);
        } catch(\Exception $e) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    public function cancelrefundAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');

        $refundMapper = RefundMapper::getInstance();
        $refundModel  = $refundMapper->findByOrder_id($orderId);

        if(!$refundModel instanceof \OrderRefundModel) {
            return \Response::error('退款不存在', 10633);
        }

        if($refundModel->getStatus() === \Lib\Consts::ORDER_REFUND_STATUS_REPLY) {
            return \Response::error('退款状态有误', 10634);
        }

        $data = [
            'status'      => \Lib\Consts::ORDER_REFUND_STATUS_DEL,
            'update_time' => time(),
        ];

        $refundMapper->begin();

        try {
            $rows = $refundMapper->update($data, [
                'order_id' => $orderId,
                'status'   => \Lib\Consts::ORDER_REFUND_STATUS_REPLY,
            ]);
        } catch(\Exception $e) {
            $rows = 0;
        }

        if($rows <= 0) {
            $refundMapper->rollback();
            return \Response::error('取消退款失败', 10641);
        }

        $return = $this->changestatus($orderId, \Lib\Consts::ORDER_STATUS_REFUNDING,
            \Lib\Consts::ORDER_STATUS_PAY);

        if(!$return) {
            $refundMapper->rollback();
            return \Response::error('取消退款失败', 10641);
        }

        $refundMapper->commit();
        return \Response::data(null);
    }

    public function refuserefundAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');

        $refundMapper = RefundMapper::getInstance();
        $refundModel  = $refundMapper->findByOrder_id($orderId);

        if(!$refundModel instanceof \OrderRefundModel) {
            return \Response::error('退款不存在', 10633);
        }

        if($refundModel->getStatus() === \Lib\Consts::ORDER_REFUND_STATUS_REPLY) {
            return \Response::error('退款状态有误', 10634);
        }

        $data = [
            'status'      => \Lib\Consts::ORDER_REFUND_STATUS_FAILED,
            'update_time' => time(),
        ];

        $refundMapper->begin();

        try {
            $rows = $refundMapper->update($data, [
                'order_id' => $orderId,
                'status'   => \Lib\Consts::ORDER_REFUND_STATUS_REPLY,
            ]);
        } catch(\Exception $e) {
            $rows = 0;
        }

        if($rows <= 0) {
            $refundMapper->rollback();
            return \Response::error('拒绝退款失败', 10642);
        }

        $return = $this->changestatus($orderId, \Lib\Consts::ORDER_STATUS_REFUNDING,
            \Lib\Consts::ORDER_STATUS_REFUND_REFUSE);

        if(!$return) {
            $refundMapper->rollback();
            return \Response::error('拒绝退款失败', 10642);
        }

        $refundMapper->commit();
        return \Response::data(null);
    }

    public function agreerefundAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');

        $refundMapper = RefundMapper::getInstance();
        $refundModel  = $refundMapper->findByOrder_id($orderId);

        if(!$refundModel instanceof \OrderRefundModel) {
            return \Response::error('退款不存在', 10633);
        }

        if($refundModel->getStatus() === \Lib\Consts::ORDER_REFUND_STATUS_REPLY) {
            return \Response::error('退款状态有误', 10634);
        }

        $data = [
            'status'      => \Lib\Consts::ORDER_REFUND_STATUS_SUCCESS,
            'update_time' => time(),
        ];

        $refundMapper->begin();

        try {
            $rows = $refundMapper->update($data, [
                'order_id' => $orderId,
                'status'   => \Lib\Consts::ORDER_REFUND_STATUS_REPLY,
            ]);
        } catch(\Exception $e) {
            $rows = 0;
        }

        if($rows <= 0) {
            $refundMapper->rollback();
            return \Response::error('同意退款申请失败', 10640);
        }

        $return = $this->changestatus($orderId, \Lib\Consts::ORDER_STATUS_REFUNDING,
            \Lib\Consts::ORDER_STATUS_REFUND_FINISH);

        if(!$return) {
            $refundMapper->rollback();
            return \Response::error('同意退款申请失败', 10640);
        }

        $refundMapper->commit();
        return \Response::data(null);
    }

    public function confirmAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');
        $status  = (int)$request->get('status');

        if($status !== \Lib\Consts::ORDER_STATUS_PAY && $status !== \Lib\Consts::ORDER_STATUS_REFUND_REFUSE) {
            return \Response::error('不能确认收货', 50000);
        }

        $return = $this->changestatus($orderId, $status, \Lib\Consts::ORDER_STATUS_FINISH);

        return $return ? \Response::data(null) : \Response::error('确认订单失败', 50000);
    }

    public function payAction() {
        $request = $this->getRequest();
        $orderId = (int)$request->get('order_id');
        $status  = (int)$request->get('status');

        if($orderId <= 0) {
            return \Response::error('订单id有误', 10608);
        }

        if($status !== \Lib\Consts::ORDER_STATUS_NOPAY) {
            return \Response::error('订单不能付款', 10643);
        }

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findById($orderId);

        if(!$orderModel instanceof \OrderModel) {
            return \Response::error('无效的订单id', 10610);
        }

        if($orderModel->getStatus() !== \Lib\Consts::ORDER_STATUS_NOPAY) {
            return \Response::error('订单不能付款', 10643);
        }

        $data = [
            'status' => \Lib\Consts::ORDER_STATUS_PAY,
        ];

        try {
            $rows = $orderMapper->update($data, [
                'id'     => $orderId,
                'status' => $status,
            ]);
            return $rows > 0 ? \Response::data(null) : \Response::error('订单付款失败', 10644);
        } catch(\Exception $e) {
            return \Response::error('异常信息报错', 10100);
        }
    }

    public function ipayAction() {
        $request = $this->getRequest();
        $orderNo = (string)$request->get('out_trade_no');
        $fail    = 'fail';

        $orderMapper = OrderMapper::getInstance();
        $orderModel  = $orderMapper->findByOrder_no($orderNo);

        if(!$orderModel instanceof \OrderModel) {
            echo $fail;
            return false;
        }

        if($orderModel->getStatus() !== \Lib\Consts::ORDER_STATUS_NOPAY) {
            echo $fail;
            return false;
        }

        if($orderModel->getStatus() !== \Lib\Consts::ORDER_STATUS_NOPAY) {
            echo $fail;
            return false;
        }

        $data = [
            'status' => \Lib\Consts::ORDER_STATUS_PAY,
        ];

        try {
            $rows = $orderMapper->update($data, [
                'id'     => $orderModel->getId(),
                'status' => $orderModel->getStatus(),
            ]);
        } catch(\Exception $e) {
            $rows = 0;
        }

        if($rows <= 0) {
            echo $fail;
            return false;
        }

        echo 'success';
        return false;
    }

}
